package ru.spbau.database.group3.types;

import java.io.Serializable;
import java.nio.ByteBuffer;

/**
 * @author: stas
 * @date: 2/4/13
 * @time: 2:06 PM
 */
public class VarcharType implements Type, Serializable {
    public VarcharType(int length) {
        this.length = length;
    }

    @Override
    public Object valueOf(String s) {
        if(s.length() > length) {
            throw new IllegalArgumentException("Very long string");
        }
        String res = s;
        if(res.charAt(0) == '\"') {
            res = res.substring(1, res.length() - 1);
        }
        while(res.length() < length) {
            res += " ";
        }
        return res;
    }


    @Override
    public int size() {
        return length * Character.SIZE / 8;
    }

    @Override
    public void writeValueToByteBuffer(ByteBuffer data, Object keyValue) {
        String value = keyValue.toString();
        for(char c : value.toCharArray()) {
            data.putChar(c);
        }
        for(int i = value.length(); i < length; ++i) {
            data.putChar(' ');
        }
    }


    @Override
    public Object readValueFromByteBuffer(ByteBuffer byteBuffer, int position) {
        char[] dst = new char[length];
        byteBuffer.position(position);
        byteBuffer.asCharBuffer().get(dst, 0, length);
        return String.valueOf(dst);
    }

    @Override
    public int compareTo(Object a, Object b) {
        if(a instanceof String && b instanceof String) {
            return ((String) a).compareTo((String) b);
        }
        throw new IllegalArgumentException("Both arguments must have the same type");
    }

    private int length;

	@Override
	public Types getTypeEnum() {
		return Types.VARCHAR;
	}
}
